<template>
  <div style="height: 100%;width: 100%">
      <div class="head">
          <p style="color: #333333;line-height: 26px;font-weight: 500;font-size: 20px">个人信息</p>
          <p style="color: #666666;line-height: 40px;font-size: 14px;margin-bottom:20px">账户设置</p>
      </div>
      <div class="item clearfix">
          <div class="userName">
            <span style="font-size: 18px;color: #333333;line-height: 34px">头像</span>
          </div>
          <div class="field-value">
              <el-avatar :src="user.headpicture" :size="48" fit="fill" class="headPicture"></el-avatar>
          </div>
          <div>
              <el-upload class="upload-demo" ref="upload" style="float: right"
                          action=""
                          accept="image/jpg,image/jpeg,image/png"
                          :file-list="fileList"
                          :auto-upload="true"
                          :show-file-list="false"
                          :on-change="mychange"
                          :limit="1"
                          :on-success="uploadsuccess" :before-upload="beforUpload"
                          :on-error="uploadError">
                    <el-button round class="btu">
                      修改
                    </el-button>
              </el-upload>

          </div>
      </div>
      <div class="item clearfix">
          <div class="userName">
            <span style="font-size: 18px;color: #333333;line-height: 34px">昵称</span>
          </div>
          <div class="field-value">
              <span style="font-size: 12px;color: #666666;line-height: 40px">{{user.username}}</span>
          </div>
          <div>
              <el-button round class="btu" @click="nameShow = true">修改</el-button>
          </div>
      </div>
      <el-dialog
          title="昵称修改"
          :visible.sync="nameShow"
          width="30%"
          center>
          <el-row style="margin: 15px auto">
              <el-col :span="10">
                  <p style="text-align: right;font-size: 14px;color: #666666;margin-right: 20px;line-height: 40px">当前昵称</p>
              </el-col>
              <el-col :span="14">
                  <p style="font-size: 14px;color: #666666;line-height: 40px">{{user.username}}</p>
              </el-col>
          </el-row>
          <el-row style="margin: 15px auto">
              <el-col :span="10">
                  <p style="text-align: right;font-size: 14px;color: #666666;margin-right: 20px;line-height: 40px">新昵称</p>
              </el-col>
              <el-col :span="14">
                  <el-input style="width: 180px" v-model="userLin.name" placeholder="请输入新昵称"></el-input>
              </el-col>
          </el-row>
          <span slot="footer" class="dialog-footer">
            <el-button @click="nameShow = false;userLin = userLin2">取 消</el-button>
            <el-button type="primary" @click="nameUp">修 改</el-button>
          </span>
      </el-dialog>

      <div class="item clearfix">
          <div class="userName">
            <span style="font-size: 18px;color: #333333;line-height: 34px">换绑手机</span>
          </div>
          <div class="field-value">
              <span style="font-size: 12px;color: #666666;line-height: 40px">{{user.phone}}</span>
          </div>
          <div>
              <el-button round class="btu" @click="phoneShow = true">换绑</el-button>
          </div>
      </div>
      <el-dialog
          title="换绑手机号"
          :visible.sync="phoneShow"
          width="30%">
          <el-form :model="userLin" ref="phoneForm" :rules="phoneRules">
              <el-form-item
                    prop="phone"
                    label="当前号码：">
                    {{user.phone}}
              </el-form-item>
              <el-form-item
                    prop="oldPhone"
                    label="输入当前号码：">
                    <el-input v-model="userLin.oldPhone" placeholder="请输入当前完整号码"></el-input>
              </el-form-item>
              <el-form-item
                    prop="newPhone"
                    label="请输入新的号码">
                  <el-input v-model="userLin.newPhone" placeholder="请输入新号码"></el-input>
              </el-form-item>
              <el-form-item
                  prop="Captcha"
                  label="验证码">
                  <el-input v-model="userLin.Captcha" placeholder="请输入验证码">
                      <el-button
                          slot="append"
                          type="primary"
                          @click="butclick(userLin.newPhone)"
                          id="but"
                          v-bind:disabled="disabled">
                          发送验证码<span v-if="time != 60">{{time}}</span>
                      </el-button>
                  </el-input>

              </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="phoneShow = false;userLin = userLin2">取 消</el-button>
            <el-button type="primary" @click="phoneForm('phoneForm')">确 定</el-button>
          </span>
      </el-dialog>

      <div class="item clearfix">
          <div class="userName">
            <span style="font-size: 18px;color: #333333;line-height: 34px">登录密码</span>
          </div>
          <div class="field-value">
              <span style="font-size: 12px;color: #666666;line-height: 40px">安全强度：{{passPower}}</span>
          </div>
          <div>
              <el-button round class="btu" @click="passShow = true">更改</el-button>
          </div>
      </div>
      <el-dialog
          title="换绑手机号"
          :visible.sync="passShow"
          width="30%">
          <el-form :model="userLin" ref="passForm" :rules="passRules">
              <el-form-item label="原密码" prop="oldPass">
                  <el-input placeholder="请输入旧密码" v-model="userLin.oldPass" show-password></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                  <el-input placeholder="请输入新密码" v-model="userLin.password" show-password></el-input>
              </el-form-item>
              <el-form-item  label="确认密码" prop="repassword">
                  <el-input placeholder="请再次输入密码" v-model="userLin.repassword" show-password></el-input>
              </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="passShow = false;userLin = userLin2">取 消</el-button>
            <el-button type="primary" @click="passForm('passForm')">确 定</el-button>
          </span>
      </el-dialog>

      <div class="item clearfix">
          <div class="userName">
            <span style="font-size: 18px;color: #333333;line-height: 34px">收货地址</span>
          </div>
          <div>
              <el-button round class="btu" @click="addressShow = true">新增</el-button>
          </div>
      </div>
      <!-- 新增收货地址-->
      <el-dialog title="新增收货地址" :visible.sync="addressShow" width="35%" style="text-align: center">
          <el-form :model="usersAddress" ref="addForm" :rules="rules">
              <el-form-item prop="address" label="收货地址" style="text-align: left">
                  <el-input v-model="usersAddress.address" placeholder="请输入收货地址"></el-input>
              </el-form-item>
              <el-form-item prop="username" label="收货人姓名" style="text-align: left">
                  <el-input v-model="usersAddress.username" placeholder="请输入收货人姓名"></el-input>
              </el-form-item>
              <el-form-item prop="userphone" label="收货人手机号" style="text-align: left">
                  <el-input v-model="usersAddress.userphone" placeholder="请输入收货人手机号"></el-input>
              </el-form-item>
          </el-form>
          <div slot="footer" style="padding: 0;text-align: center;height: 50px">
              <el-button @click="addUsersAddressActive = false;userLin = userLin2">取 消</el-button>
              <el-button type="primary" @click="onsubmitForm('addForm')">确 定</el-button>
          </div>
      </el-dialog>
  </div>

</template>

<script>
import user from '@/api/users'
export default {
    data(){
        let validate = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入当前绑定手机号'))
            } else if (value !== JSON.parse(sessionStorage.getItem('users')).phone) {
                callback(new Error('与原号码不一致'))
            } else {
                callback()
            }
        }
        let validate2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入当前登录密码'))
            } else if (value !== JSON.parse(sessionStorage.getItem('users')).loginpassword) {
                callback(new Error('与原密码不一致'))
            } else {
                callback()
            }
        }
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.userLin.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        return{
            user:{
                id:'',
                username:'',
                loginpassword:'',
                headpicture:'',
                phone:'',
                authority:'',
                paypassword:'',
                address:''

            },
            passPower:'',
            fileList:[],
            nameShow:false,
            phoneShow:false,
            userLin:{
                name:'',
                phone:'',
                oldPhone:'',
                newPhone:'',
                Captcha:'',
                oldPass:'',
                password:'',
                repassword:''
            },
            userLin2:{
                name:'',
                phone:'',
                oldPhone:'',
                newPhone:'',
                Captcha:'',
                oldPass:'',
                password:'',
                repassword:''
            },
            addressShow:false,
            //收货地址################
            usersAddress:{
                uid:'',
                address:'',
                username:'',
                userphone:'',
            },
            addUsersAddressActive:false,
            rules:{
                address:{required: true, message: '收货地址不能为空',trigger: 'blur'},
                username: {required: true, message: '收货人姓名不能为空',trigger: 'blur'},
                userphone: {required: true, message: '收货人手机号不能为空',trigger: 'blur'},
            },
            phoneRules:{
                oldPhone: {required:true,validator:validate,trigger:'blur'},
                newPhone:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: ['blur','change'] }
                ],
                Captcha: { required: true, message: '请输入验证码', trigger: 'blur' }
            },
            disabled:false,
            yan:'',
            time:60,
            passShow:false,
            passRules:{
                oldPass: {required:true,validator:validate2,trigger:'blur'},
                password: [
                    { required: true, message: '密码不能为空', trigger: 'blur' },
                ],
                repassword: [
                    { required: true, validator: validatePass2, trigger: ['blur','change'] }
                ]
            }
        }
    },
    methods:{
        regex(){
            //密码为八位及以上并且字母数字特殊字符三项都包括
            var strongRegex = new RegExp("^(?=.{6,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
            //密码为八位及以上并且字母、数字、特殊字符三项中有两项，强度是中等
            var mediumRegex = new RegExp("^(?=.{6,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*\\W))).*$", "g");
            var enoughRegex = new RegExp("(?=.{6,}).*", "g");
            if(strongRegex.test(this.user.loginpassword)) {
                this.passPower="高"
            } else if (mediumRegex.test(this.user.loginpassword)){
                this.passPower="中"
            } else if(enoughRegex.test(this.user.loginpassword)){
                this.passPower="低"
            }
        },
        mychange(file,fileList){
            this.getBase64(file.raw).then(res=>{
                if (this.user.headpicture !== res){
                    this.user.headpicture = res
                    this.update()
                }
            })

        },
        getBase64(file){
            return new Promise(function (resolve, reject) {
                const reader = new FileReader()
                let imgResult = ''
                reader.readAsDataURL(file)
                reader.onload = function () {
                    imgResult = reader.result
                }
                reader.onerror = function (error) {
                    reject(error)
                }
                reader.onloadend = function () {
                    resolve(imgResult)
                }
            })
        },
        uploadsuccess(response){
            this.flag = true;
            this.$refs.upload.clearFiles();

        },
        uploadError(){
            this.flag = false;
        },
        beforUpload(file){
            if(!(file.type==='image/png')&&!(file.type==='image/jpeg')&&!(file.type==='image/jpg')){
                this.$message.error('只能上传图片')
                return false
            }
        },
        update(){
            let that = this
            this.user.phone = JSON.parse(sessionStorage.getItem('users')).phone;
            user.updateMyInformation(this.user).then(response=>{
                let i = response.data.data;
                if(i>0){
                    console.log("success")
                    user.login(that.user.phone,that.user.loginpassword).then(response=>{
                        let user = response.data.data
                        that.resetSetItem("users",JSON.stringify(user));
                    })
                }else{
                    console.log("失败")
                }
            })
        },
        updateUser(){
            console.log(5556655)
            let user = JSON.parse(sessionStorage.getItem('users'));
            this.user.id = user.id;
            this.user.username = user.username;
            this.user.loginpassword = user.loginpassword;
            this.user.headpicture = user.headpicture;
            user.phone = user.phone.substring(0,3)+'****'+user.phone.substring(7,11)
            this.user.phone = user.phone;
            this.user.authority = user.authority;
            this.user.paypassword = user.paypassword;
            this.user.address = user.address;
            this.regex();
        },
        nameUp(){
            console.log(this.userLin.name)
            if (this.userLin.name===null || this.userLin.name===''){
                this.$message.error('新昵称不能为空')
            }else{
                this.user.username = this.userLin.name;
                this.update();
                this.userLin = this.userLin2;
                this.nameShow = false;
            }
        },
        onsubmitForm(formName){
            let that = this;
            this.$refs[formName].validate((valid)=>{
                if (valid){
                    that.usersAddress.uid = JSON.parse(sessionStorage.getItem('users')).id
                    user.addUsersAddress(that.usersAddress).then(response=>{
                        if (response.data.data>0){
                            that.$message({
                                message: '新增成功',
                                type: 'success'
                            });
                        }else{
                            that.$message({
                                message: '新增失败，请稍后尝试',
                                type: 'warning'
                            });
                        }
                        that.addressShow = false;
                    })
                }else{
                    this.$message({
                        message: '新增失败，请检查未填项',
                        type: 'warning'
                    });
                }
            })
        },
        butclick(phone){
            var _this=this;
            this.time=60;
            var zhengze=/^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/;
            if(zhengze.test(phone)){
                _this.mounted();
                this.disabled=true;
                user.sendMsm(phone).then(function(response){
                    // console.log(response.data.data)
                    _this.yan = response.data.data;
                    // console.log(_this.yan);
                })
            }else{
                alert("请输入正确的手机号");
            }
        },
        phoneForm(formName) {
            var that=this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(that.yan==that.userLin.Captcha){
                        that.user.phone = that.userLin.newPhone;
                        that.update()
                    }
                    this.userLin = this.userLin2;
                    that.phoneShow = false
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        mounted(){
            //在mounted 声明周期中创建定时器
            const timer = setInterval(()=>{
                // 这里调用需要执行的方法
                if(this.time>0){
                    this.time=this.time-1;
                }else{
                    this.disabled=false;
                    this.time = 60;
                }
            }, 1000) // 每一秒执行1次
            // 通过$once来监听定时器，在beforeDestroy钩子可以被清除
            this.$once('hook:beforeDestroy',()=>{
                // 在页面销毁时，销毁定时器
                clearInterval(timer)
            })
        },
        passForm(formName){
            var that=this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    that.user.loginpassword = that.userLin.password;
                    that.update()
                    that.passShow = false
                    that.$message({
                        message: '密码改变成功',
                        type: 'success'
                    });
                    this.userLin = this.userLin2;
                } else {
                    console.log('error submit!!');
                    that.$message({
                        message: '密码改变失败',
                        type: 'warning'
                    });
                    return false;
                }
            });
        }
    },
    created() {
        this.updateUser();
        window.addEventListener('setItem',this.updateUser)
    },

}
</script>

<style scoped>
.item{
    border-top: 1px solid #E5E5E5;
    padding: 30px 0;
}
.clearfix:after {
    content: " ";
    visibility: hidden;
    display: block;
    height: 0;
    clear: both;
}
.userName{
    width: 95px;
    border-right: 1px solid #e5e5e5;
    text-align: right;
    padding-right: 30px;
    float: left;
}
.field-value{
    float: left;
    text-align: right;
    padding-left: 30px;
    height: 40px;
}
.headPicture{
    transform: translateY(-5px);
}
.btu{
    padding: 0;
    font-size: 14px;
    color: #666666;
    float: right;
    height: 40px;
    width: 82px;
    cursor: pointer;
    margin: 0 15px;
    line-height: 40px;
    text-align: center;
    background-color: #ffffff;
}
.btu:hover{
    color: #666666;
    background-color: #fff;
    border: 1px solid #E5E5E5;
}
.btu:focus{
    color: #666666;
    background-color: #fff;
    border: 1px solid #E5E5E5;
}
::v-deep .el-button.is-round{
    padding: 0;
}
</style>